package cn.jiangxiong.pethome.base.controller;

import cn.jiangxiong.pethome.base.query.BaseQuery;
import cn.jiangxiong.pethome.base.service.IBaseService;
import cn.jiangxiong.pethome.utils.AjaxResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

public class BaseController<T> {

        @Autowired
        private IBaseService<T> baseService;

        @PostMapping("/list")
        @ApiOperation(value = "获取所有的信息" )
        public List<T> findAll(){
            return baseService.findAll();
        }

        @GetMapping("/{id}")
        @ApiOperation(value = "根据id查询")
        public AjaxResult findOne(@PathVariable("id") Long id){
            try {
                T one = baseService.findOne(id);
                return AjaxResult.success().setData(one);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return AjaxResult.error();
        }

        @PostMapping("/pagelist")
        @ApiOperation(value = "分页查询")
        public AjaxResult findQuery(@RequestBody BaseQuery query){
            try {
                List<T> byQuery = baseService.findByQuery(query);
                Long count = baseService.findByQueryCount(query);
                return AjaxResult.success().setData(byQuery).setTotal(count);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return AjaxResult.error();
        }

        @DeleteMapping("/{id}")
        @ApiOperation(value = "根据id删除")
        public AjaxResult delete(@PathVariable("id") Long id){
            try {
                baseService.delete(id);
                return AjaxResult.success().setMsg("删除成功");
            }catch (Exception e){
                e.printStackTrace();
                return AjaxResult.error().setMsg(e.getMessage());
            }
        }

        @PostMapping
        @ApiOperation(value = "添加数据")
        public AjaxResult add(@RequestBody T t){
            try {
                baseService.add(t);
                return AjaxResult.success();
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error().setMsg(e.getMessage());
            }

        }

        @PutMapping
        @ApiOperation(value = "修改数据")
        public AjaxResult update(@RequestBody T t){
            try {
                baseService.update(t);
                return AjaxResult.success();
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error().setMsg(e.getMessage());
            }
        }

}
